package com.longteng.java.web.dao.impl;

import com.google.common.base.Preconditions;
import com.longteng.java.web.dao.UserDao;
import com.longteng.java.web.model.UserEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by tianqing.wang
 * DATE : 2018/4/15
 * TIME : 上午2:03
 * PROJECT : web-lesson
 * PACKAGE : com.longteng.java.web.dao.impl
 *
 * @author <a href="mailto:celeskyking@163.com">tianqing.wang</a>
 */
@Repository
public class UserDaoImpl implements UserDao{

    @Resource
    private JdbcTemplate jdbcTemplate;


    private SimpleJdbcInsert simpleJdbcInsert;


    @PostConstruct
    public void init(){
        this.simpleJdbcInsert = new SimpleJdbcInsert(Preconditions.checkNotNull(jdbcTemplate.getDataSource()))
                .withTableName("user");
    }


    @Override
    public List<UserEntity> selectAll() {
        return jdbcTemplate.query("select * from user", new UserMapper());
    }

    @Override
    public Integer inserUser(UserEntity user) {
        SqlParameterSource sqlParameterSource = new MapSqlParameterSource()
                .addValue("name","tianqing.wang");
        return simpleJdbcInsert.executeAndReturnKey(sqlParameterSource).intValue();
    }



    public static class UserMapper implements RowMapper<UserEntity> {

        @Override
        public UserEntity mapRow(ResultSet resultSet, int i) throws SQLException {
            UserEntity userEntity = new UserEntity();
            userEntity.setName(resultSet.getString("name"));
            return userEntity;
        }
    }
}
